//
//  ResetCipherController.swift
//  YiYaoHui
//
//  Created by HM on 15/12/5.
//  Copyright © 2015年 TMPercy. All rights reserved.
//

import UIKit
import Alamofire

class ResetCipherController: UIViewController {
    
    @IBOutlet weak var cipherForResetTF: UITextField!
    
    @IBOutlet weak var confirmTF: UITextField!

    @IBOutlet weak var resetButton: UIButton!
    
    @IBOutlet weak var contentView: UIView!
    
    let baseURL = "http://112.74.131.194:8080/MedicineProject/App/getBackPassword"
    var cipher:NSString!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        cipherForResetTF.delegate = self
        confirmTF.delegate = self
        
        setUpUI()
    }
    
    func setUpUI() {
        disableButton()
        contentView.layer.borderWidth = 1.0
        contentView.layer.borderColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1).CGColor
        resetButton.layer.cornerRadius = 5
    }
    
    
    func enableButton() {
        resetButton.enabled = true
        resetButton.backgroundColor = UIColor(red: 96/255, green: 200/255, blue: 75/255, alpha: 1)
        resetButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    }
    
    func disableButton() {
        resetButton.enabled = false
        resetButton.backgroundColor = UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 1.0)
        resetButton.setTitleColor(UIColor.lightTextColor(), forState: UIControlState.Disabled)
    }
    
    
    //
    override func viewWillAppear(animated: Bool) {
        
        //去掉箭头右边文字
        UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -60), forBarMetrics: .Default)
        
        navigationController?.navigationBarHidden = false
        self.navigationController?.navigationBar.backItem?.title = ""
        self.title = "重置密码"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func resetCipher(sender: AnyObject) {
        
        //编辑完了按空白处收键盘
        dismissKeyboard()
        
        //手机号不能为空
        if ((cipherForResetTF.text != nil  && confirmTF.text != nil) && (cipherForResetTF.text != "" && confirmTF.text != "")) {
            Alamofire.request(.POST, baseURL, parameters: ["newPassword":confirmTF.text!], encoding: .URL, headers: nil).responseJSON { (_, _, result) -> Void in
                //先判断返回的值是否为空，不为空就执行这一步
                if let  value = result.value {
                    //再判断返回的值是success还是fail
                    let state = value["result"] as! String
                    if state == "success" {
//                        NSUserDefaults.standardUserDefaults().setValue(self.cipher, forKey: "cipher")
//                        NSUserDefaults.standardUserDefaults().synchronize()
                        let alert = UIAlertController(title: "提示", message: "重置密码成功！", preferredStyle: UIAlertControllerStyle.Alert)
                        //请求成功则按“确定后”跳到登录页面重新登录，在登录页面保存新密码
                        let action = UIAlertAction(title: "确定", style: .Default, handler: { (alertAction) -> Void in
                            let loginController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginController") as! LoginController
                            self.navigationController?.pushViewController(loginController, animated: true)

                        })
                        alert.addAction(action)
                        self.presentViewController(alert, animated: true, completion: nil)
                        
                        print(result.value)
                    } else { //如果返回fail
                        self.alertView()
                    }
                }
                else { //如果返回nil
                    self.alertView()
                }
            }
        } else {
            self.disableButton()
        }
    }
    
    func alertView() {
        let alert = UIAlertController(title: "两次密码不一致", message: "请重新输入", preferredStyle: UIAlertControllerStyle.Alert)
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

//text field 的
extension ResetCipherController : UITextFieldDelegate {
    func dismissKeyboard() {
        cipherForResetTF.resignFirstResponder()
        confirmTF.resignFirstResponder()
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        dismissKeyboard()
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        dismissKeyboard()
        textField.text = textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        dismissKeyboard()
        textField.text = textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        if (confirmTF.text != nil && confirmTF.text != "") {
            self.enableButton()
        } else {
            self.disableButton()
        }
    }

}
